import React, { useCallback } from 'react';
import { useProvide, useInject } from '@/hooks/useShare';
import useDraft from '@/hooks/useDraft';

import styles from './useShare.css';

function Sub1() {
  const [state] = useInject('/experiment/useProvideInject');
  return <pre className={styles.left}><h2>Sub1</h2>{JSON.stringify(state, null, 2)}</pre>;
}

function Sub2() {
  const [state] = useInject('/experiment/useProvideInject');
  const [currentDeal] = useInject('/currentDeal');
  return (
    <div className={styles.left}>
      <h2>Sub2</h2>
      <pre>{JSON.stringify(state, null, 2)}</pre>
      <pre>{JSON.stringify(currentDeal, null, 2)}</pre>
    </div>
  );
}

function Main() {
  // 1. 从共享状态先还原
  const [savedState] = useInject('/experiment/useProvideInject', () => ({ a: 1, b: 2 }));
  // 2. 然后开始 local state 管理
  const [state, setDraft] = useDraft(savedState);
  // 3. 再共享给外部
  useProvide('/experiment/useProvideInject', state, false);

  const cb1 = useCallback(() => {
    setDraft((d: any) => {
      d.a++;
    });
  }, []);
  const cb2 = useCallback(() => {
    setDraft((d: any) => {
      d.b++;
    });
  }, []);

  return (
    <div className={styles.left}>
      <h2>Main</h2>
      <div>
        <button onClick={cb1}>cb1</button>
        <button onClick={cb2}>cb2</button>
      </div>
      <pre>{JSON.stringify(state, null, 2)}</pre>
    </div>
  );
}

export default function UseShare() {
  const env = {
    serviceCode: '0010',
    stageType: 2,
  };
  useProvide('/currentDeal', env);
  const [state] = useInject('/experiment/useProvideInject');
  return (
    <div className={styles.normal}>
      <h1>Page useShare</h1>
      <Main />
      <hr />
      {state?.a <= 3 && <Sub1 />}
      <hr />
      {state?.b <= 3 && <Sub2 />}
    </div>
  );
}
